package top.frsf.reggie.controller;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import top.frsf.reggie.common.R;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.UUID;

/**
 * @Author FRSF
 * @Date 2023/1/16 13:03
 * @Description 文件上下传
 */

@Slf4j
@RestController
@RequestMapping("/common")
public class CommonController {

    @Value("${reggie.path}")
    private String base_path;


    /**
     * @Author: FRSF
     * @Date: 2023/1/16 13:22
     * @Description 文件上传
     * @param file: 文件
     * @return: top.frsf.reggie.common.R<java.lang.String>
     */
    @PostMapping("/upload")
    public R<String> upload(MultipartFile file) {
        // file是一个临时文件，需要转存到指定位置，否则本次请求完成后临时文件会删除
        String originalFilename = file.getOriginalFilename();
        log.info("用户文件上传:{}", originalFilename);

        // 文件类型截取
        String fileType = originalFilename.substring(originalFilename.lastIndexOf("."));

        // 使用UUID重新生成文件名，防止文件名称重复造成文件覆盖
        String fileName = UUID.randomUUID().toString() + fileType;

        // 判读目录是否存在
        File temp = new File(base_path);
        if (!temp.exists()) {
            temp.mkdir();
        }

        try {
            file.transferTo(new File(base_path + fileName));
        } catch (IOException e) {
            e.printStackTrace();
        }

        // 返回生成的文件名称
        return R.success(fileName);
    }


    /**
     * @Author: FRSF
     * @Date: 2023/1/16 14:35
     * @Description 文件下载
     * @param name:
     * @param response: 直接返回输出流到前端<img>
     * @return: void
     */
    @GetMapping("/download")
    public void download(String name, HttpServletResponse response) {
        try {
            // 输入流，读取文件内容
            FileInputStream fileInputStream = new FileInputStream(new File(base_path + name));

            // 输出流，将文件写回浏览器
            ServletOutputStream outputStream = response.getOutputStream();
            response.setContentType("image/jpeg");

            int len = 0;
            byte[] bytes = new byte[1024];
            while ((len = fileInputStream.read(bytes)) != -1) {
                outputStream.write(bytes, 0, len);
                outputStream.flush();
            }
            outputStream.close();
            fileInputStream.close();

        } catch (Exception e) {
            e.printStackTrace();
        }


    }

}
